﻿using B.S.PrimaryProject.Infrastructure.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace B.S.PrimaryProject.Infrastructure.Implements
{
    public class BaseRepository<T>:IBaseRepository<T> where T : class
    {
        PrimaryDbContext db;

        public BaseRepository(PrimaryDbContext db)
        {
            this.db = db;
        }

        public async Task<int> AddAsync(T entity)
        {
            try
            {
                await db.Set<T>().AddAsync(entity);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public IQueryable<T> GetAll()
        {
            try
            {
                return db.Set<T>().AsQueryable();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<T> GetAsync(Expression<Func<T, bool>> expression)
        {
            try
            {
                return await db.Set<T>().Where(expression).FirstOrDefaultAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<int> UpdAsync(T entity)
        {
            try
            {
                db.Set<T>().Update(entity);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
